0
我被卡住了,看起来很容易。我想创建一个包含两个按钮的简单应用程序:一个用于启动服务,另一个用于停止它。我已经建立了我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
代码:每次我模拟时间
<?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>
不幸的是,:
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);
}
而且清单通过Android Device Monitor
发送短信,它不起作用,它向我显示了默认的系统通知(即使没有清单中的权限也会显示该通知) IST是正确的行为)
编辑: 在Android Device Monitor
它仍保持舒Permission Denial: ... requires android.permission.RECEIVE_SMS due to sender.com android...
。然而,我已经将其添加到意向过滤器中,然后我不知道它为什么会发生。