我遇到了一些看似简单的事情。我想创建一个包含两个按钮的简单应用程序:一个用于启动服务,另一个用于停止服务。我创建了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
不幸的是,每当我模拟通过Android Device Monitor
发送短信时,它都不起作用,它会向我显示默认的系统通知(顺便提一下,即使没有明确的许可 - 这是正确的行为吗?)
修改
在Permission Denial: ... requires android.permission.RECEIVE_SMS due to sender.com android...
中,它仍然保持showin {{1}}。然而,我已将此添加到intent filter中,然后我不知道它为什么会发生。
答案 0 :(得分:0)
这个问题的答案与我上次获得权限的其他一些事项有关,而且它与Marshmallow的新许可政治有关。更多信息here。
所以问题可以通过在运行时切换到较低的sdk版本或调用appriopriate方法(查看上面的链接)来解决。