我被一些看似简单的东西困住了。我想要创建一个简单的应用程序,其中包含两个按钮:一个启动服务,另一个停止服务。我创建了我的NotifyService类:
public class NotifyService extends Service {
public NotifyService() {
}
private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
displayNotification(intent);
}
};
private void displayNotification(Intent intent)
{
if(intent.getAction().equals(SMS_RECEIVED)) {
int NOTIFICATION=R.string.local_service_started;
//notification creating
Notification.Builder notificationBuilder = new Notification.Builder(this)
.setContentText("Otrzymano smsa!")
.setContentTitle("SMS!")
.setSmallIcon(android.R.drawable.btn_plus);
Notification note = notificationBuilder.build();
//getting system service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//displaying notification
notificationManager.notify(NOTIFICATION, note);
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
@Override
public void onCreate() {
super.onCreate();
registerReceiver(broadcastReceiver,new IntentFilter(SMS_RECEIVED));
}
@Override
public IBinder onBind(Intent intent) {
return null;
}这是我的MainActivity代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startServiceBtn(View view)
{
Intent intent = new Intent(this,NotifyService.class);
startService(intent);
}
public void stopServiceBtn(View view)
{
Intent intent = new Intent(this,NotifyService.class);
stopService(intent);
}以及清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pablo.myapplication" >
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NotifyService"
android:enabled="true"
android:exported="true" >
</service>
</application>不幸的是,每次我模拟通过Android Device Monitor发送短信时,它都不能工作,它会显示默认的系统通知(顺便说一句,即使没有清单中的许可,对吗?)
编辑: In Android Device Monitor,它仍然在播放Permission Denial: ... requires android.permission.RECEIVE_SMS due to sender.com android...。但是,我已经将它添加到意图过滤器中,然后我不知道为什么会发生这种情况。
发布于 2015-12-05 20:24:11
这个问题的答案与我上一次拥有权限的其他一些问题有关,它与与Marshmallow的新许可政治有关。更多信息,here。
因此,可以通过切换到更低的sdk版本或在运行时调用appriopriate方法(查看上面的链接)来解决这个问题。
https://stackoverflow.com/questions/33540766
复制相似问题