我正在尝试创建一个响应耳机点击事件的应用。每当我按下耳机按钮时,它会广播一个意图,我的服务开始在后台运行。但是,一旦我打电话是否连接了耳机,就不会播放按钮按下的意图,简单的音乐播放器应用程序以按下按钮开始,这是耳机按钮的默认功能。我是广播接收器和关键事件的新手,所以我无法弄清楚我错在哪里。请告知如何解决这个问题。这是我的ForeverBroadcastReceiver.java文件
<div class="x_panel">
<div class="x_title">
<h2>{{JobTitle}}<small></small></h2>
<div class="clearfix"></div>
</div>
<div class="x_content col-md-12">
<div class="row col-md-12 data-tablex">
<div class="col-md-offset-8 col-md-4 col-sm-12 col-xs-12 data-tablex data-tabley">
<input type="text" class="form-control" placeholder="Search" ng-model="search" />
</div>
<div class="col-md-offset-8 col-md-4 col-sm-12 col-xs-12 data-tablex data-tableym">
<form action="{{Action}}" method="post" class="frm-export" id="frmexport">
@{Html.RenderAction("Filter", "Job");}
<input type="submit" value="Export" class="btn-export" id="btnexport" />
<a href="" class="toggle-filter"><i class="fa fa-list"></i> Filter</a>
<a href="javascript:document.getElementById('btnexport').click();"><i class="fa fa-list"></i> Export</a>
@* <button type="submit" class="btn btn-success" ng-click="Export(Jobs)">Export</button>*@
</form>
</div>
<div class="col-md-offset-8 col-md-4 col-sm-12 col-xs-12 data-tablex data-tableyr">
<p class="text-right">
<strong>page: {{tableParams.page()}} of {{tableParams.total()/tableParams.count()}}</strong>
</p>
</div>
<div class="form-group form-filter">
<div class="col-md-12 col-sm-12 col-xs-12 col-md-offset-0 row table-filter">
<form action="{{Action}}" method="post" class="frm-exportx">
@{Html.RenderAction("Filter", "Job");}
</form>
</div>
</div>
<div class="col-md-12 col-sm-12 colxs12 data-tablex" style="">
<table id="tblAllJobs" class="ng-table-responsive table table-striped table-bordered table-jobs" ng-table="tableParams" template-pagination="custom/pager">
<tr ng-repeat="Job in $data | filter:search">
<td data-title="'Job'" sortable="'JobNum'">
<a href="/#/EditJob" ng-click="editJob(Job.JobNum)">{{ Job.JobNum }}</a>
</td>
<td data-title="'Priority'" sortable="'Priority'">
{{ Job.Priority }}
</td>
<td data-title="'Staff'" sortable="'Staff'">
{{ Job.Staff }}
</td>
<td data-title="'Title'" sortable="'JobName'">
{{ Job.JobName }}
</td>
<td data-title="'Company'" sortable="'Company'">
{{ Job.Company}}
</td>
<td data-title="'Deadlines'" sortable="'Deadlines'">
{{ Job.Deadlines}}
</td>
<td data-title="'Status'" sortable="'StatusComment'">
{{ Job.StatusComment}}
</td>
<td data-title="'Copy'" class="td-center"><a href="/#/CreateAsNewJob" ng-click="CreateAsNewJob(Job.JobNum)"><i class="fa fa-plus"></i></a></td>
@* <td data-title="'Edit'"><a ng-click="editJob(Job.JobNum)"><i class="fa fa-pencil"></i></a></td>*@
</tr>
@* <tr class="noRecordMsg" ng-hide="$data.length"><td colspan="7" align="center">No Jobs available</td></tr>*@
<tr class="noRecordMsg" ng-hide="$data.length"><td colspan="8" align="center">No Jobs available</td></tr>
</table>
</div>
</div>
</div>
</div>
<script type="text/ng-template" id="custom/pager">
<ul class="pager ng-cloak">
<li ng-repeat="page in pages"
ng-class="{'disabled': !page.active, 'previous': page.type == 'prev', 'next': page.type == 'next'}"
ng-show="page.type == 'prev' || page.type == 'next'" ng-switch="page.type">
<a ng-switch-when="prev" ng-click="params.page(page.number)" href="">« Previous</a>
<a ng-switch-when="next" ng-click="params.page(page.number)" href="">Next »</a>
</li>
<li>
<div class="btn-group">
<button type="button" ng-class="{'active':params.count() == 5}" ng-click="params.count(5)" class="btn btn-default">5</button>
<button type="button" ng-class="{'active':params.count() == 10}" ng-click="params.count(10)" class="btn btn-default">10</button>
<button type="button" ng-class="{'active':params.count() == 20}" ng-click="params.count(20)" class="btn btn-default">20</button>
<button type="button" ng-class="{'active':params.count() == 50}" ng-click="params.count(50)" class="btn btn-default">50</button>
</div>
</li>
</ul>
</script>
ForeverService.java类
public class ForeverBroadcastReceiver extends BroadcastReceiver {
private PendingIntent pendingIntent;
@TargetApi(24)
@Override
public void onReceive(Context context, Intent intent) {
Log.i("ForeverServiceReceiver" ,"Inside broadcast Receiver");
Intent myIntent = new Intent(context, ForeverService.class);
pendingIntent = PendingIntent.getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
// alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,1000,100,pendingIntent);
Toast.makeText(context, "Start Alarm SERVICE IS UP", Toast.LENGTH_LONG).show();
}
}
MainActivity.java
public class ForeverService extends Service {
private MediaPlayer player;
public static boolean IS_SERVICE_RUNNING = false;
private static final String LOG_TAG = "ForeverService";
public ForeverService() {
}
@Override
//will get started when service will start
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void onCreate(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new android.support.v4.app.NotificationCompat.Builder(this)
.setContentTitle("My awesome app")
.setContentText("Doing some work...")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build();
startForeground(1337, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null; //because we dont want to bind service with the activity
// TODO: Return the communication channel to the service.
}
}
的AndroidManifest.xml
public class MainActivity extends AppCompatActivity {
private Button start, stop;
AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.buttonStart);
stop = (Button) findViewById(R.id.buttonStop);
//start listening for button clicks
}
@Override
public void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "permission not granted", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
} else {
Toast.makeText(this, "Permission is granted", Toast.LENGTH_SHORT).show();
}
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
audioManager.registerMediaButtonEventReceiver(new ComponentName(this, ForeverBroadcastReceiver.class));
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == 123){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(getApplicationContext(), "permission granted ", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "permission has been denied or request cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}